package com.vedana.bankmobile.tests;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import com.google.protobuf.Descriptors.MethodDescriptor;
import com.google.protobuf.Message;
import com.google.protobuf.RpcCallback;
import com.google.protobuf.RpcChannel;
import com.google.protobuf.RpcController;

/**
 * Basic HTTP channel for protobuf RPC.
 * 
 * @author Didier MOISE
 */
public class HttpRpcChannel implements RpcChannel {
	private String uri;

	final HttpClient client = new DefaultHttpClient();
	
	public HttpRpcChannel(String uri) {
		this.uri = uri;
	}
	@Override
	public void callMethod(MethodDescriptor method, RpcController controller,
			Message request, Message responsePrototype,
			RpcCallback<Message> done) {
        try
        {
          HttpPost post = new HttpPost(uri);
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          DataOutputStream dos = new DataOutputStream(baos);
          dos.writeInt(method.getIndex());
          dos.writeInt(request.getSerializedSize());
          request.writeTo(dos);
          dos.flush();
          byte[] toSend = baos.toByteArray();
          post.setEntity(new ByteArrayEntity(toSend ));

          HttpResponse response = client.execute(post);
          
          InputStream in = response.getEntity().getContent();
          DataInputStream dis = new DataInputStream(in);
          int size = dis.readInt();
          byte[]array = new byte[size];
          if (size > 0) {
        	  dis.readFully(array);
          }
          dis.close();
          done.run(responsePrototype.newBuilderForType().mergeFrom(array).build());
        }
        catch (IOException e)
        {
          e.printStackTrace();
        }
		
	}

}
